import Request from 'luch-request'
import store from '@/store/index.js'
import utils from '@/utils/index.js'
import dayjs from '@/js_sdk/dayjs/dayjs.min.js'

export const http = new Request()

// HTTP可选配置数组
export const configList = [{
		name: '生产',
		baseURL: 'https://agedmall.ejiakanghu.cn/assistant',
		header: {
			'content-type': 'application/x-www-form-urlencoded'
		},
		method: 'POST',
		dataType: 'json',
		// #ifndef MP-ALIPAY
		responseType: 'text',
		// #endif
		custom: {
			showLoading: true,
			mock: false,
			requestIntercept: true,
			responseIntercept: true,
			checkInited: true,
		}, // 全局自定义参数默认值
		// #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
		timeout: 30000,
		// #endif
	},
	{
		name: '测试',
		baseURL: 'https://wldata.ejiakanghu.cn/assistant',
		header: {
			'content-type': 'application/x-www-form-urlencoded'
		},
		method: 'POST',
		dataType: 'json',
		// #ifndef MP-ALIPAY
		responseType: 'text',
		// #endif
		custom: {
			showLoading: true,
			mock: false,
			requestIntercept: true,
			responseIntercept: true,
			checkInited: true,
		}, // 全局自定义参数默认值
		// #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
		timeout: 30000,
		// #endif
	},
]

// 设置HTTP全局配置
export function initHttpConfig(tag) {
	console.log('初始化HTTP配置：' + tag)

	let apiIndex = utils.getStorageSync('api-index')
	console.log('当前 apiIndex = ' + apiIndex)

	if (!apiIndex || apiIndex < 0 || apiIndex > configList.length) {
		http.setConfig((config) => {
			return configList[0]
		})
		console.log(`★★★ 当前 ${configList[0].name} API接口地址：${configList[0].baseURL} ★★★`)
	} else {
		http.setConfig((config) => {
			return configList[apiIndex]
		})
		console.log(`★★★ 当前 ${configList[apiIndex].name} API接口地址：${configList[apiIndex].baseURL} ★★★`)
	}
}

// 获取图片上传接口地址
export function getUploadImageUrl() {
	// #ifdef MP-WEIXIN
	let apiIndex = utils.getStorageSync('api-index')
	
	// return 'https://agedmall.ejiakanghu.cn/common/uploadImage'
	
	if (__wxConfig.envVersion == 'release' || !apiIndex || apiIndex < 0 || apiIndex > configList.length) {
		return `${configList[0].baseURL}/common/uploadImage`
	} else {
		return `${configList[apiIndex].baseURL}/common/uploadImage`
	}
	// #endif
	
	// #ifdef MP-ALIPAY
	let apiIndex = utils.getStorageSync('api-index')
	if (!apiIndex || apiIndex < 0 || apiIndex > configList.length) {
		return `${configList[0].baseURL}/common/uploadImage`
	} else {
		return `${configList[apiIndex].baseURL}/common/uploadImage`
	}
	// #endif
	
	// #ifdef MP-TOUTIAO
	let apiIndex = utils.getStorageSync('api-index')
	if (tt.getEnvInfoSync().microapp.envType == 'production' || !apiIndex || apiIndex < 0 || apiIndex > configList.length) {
		return `${configList[0].baseURL}/common/uploadImage`
	} else {
		return `${configList[apiIndex].baseURL}/common/uploadImage`
	}
	// #endif
}

// 获取公共请求头参数
export function getPublicHeader() {
	let ctype

	// #ifdef MP-WEIXIN
	ctype = 'WEIXIN'
	// #endif

	// #ifdef MP-ALIPAY
	ctype = 'ALIPAY'
	// #endif

	let headers = {
		'ctype': ctype.toString(),
	}

	if (store.getters.userInfo && !utils.isEmpty(store.getters.userInfo.token)) {
		headers['token'] = store.getters.userInfo.token.toString()
	}

	// 客户端当前UNIX时间戳，单位秒
	headers['timestamp'] = utils.timestamp()

	return headers
}

// 检测网络连接是否可用
export function checkNetworkStatus() {
	return utils.isNetworkConnected()
}

// HTTP请求前拦截器
http.interceptors.request.use(async (config) => {
	console.log('★★★ HTTP请求前拦截器 ★★★', config)

	if (config.custom.showLoading) {
		uni.showLoading({
			title: '正在加载中'
		})
	}

	let network = await checkNetworkStatus()

	// #ifdef MP-WEIXIN
	if (!network || network.networkType == 'none' || network.networkType == 'unknown') {
		if (config.custom.showLoading) {
			uni.hideLoading()
		}
		console.log('微信无网络')
		return Promise.reject('网络连接不可用，请检查网络设置')
	}
	// #endif

	// #ifdef MP-ALIPAY
	if (!network || !network.networkAvailable) {
		if (config.custom.showLoading) {
			uni.hideLoading()
		}
		console.log('支付宝无网络')
		return Promise.reject('网络连接不可用，请检查网络设置')
	}
	// #endif

	if (config.custom.mock) {
		config.baseURL = 'https://mockapi.eolink.com/5Vh8hji2c73d29937d8683fdf8fac88ea23cdb6865d3229'
	}

	if (!config.custom.requestIntercept) {
		console.log('★★★ 跳过HTTP请求前拦截器 ★★★')
		return config
	}

	config.header = {
		...getPublicHeader(),
		...config.header,
	}
	
	console.log('★★★ HTTP请求配置对象 ★★★', config)
	
	return config
}, config => {
	return Promise.reject(config)
})

// HTTP请求后拦截器
http.interceptors.response.use((response) => {
	console.log('★★★ HTTP请求响应成功 ★★★', response)

	if (!response) {
		return Promise.reject('网络请求失败，请检查网络连接是否可用')
	}

	if (response.config && response.config.custom.showLoading) {
		uni.hideLoading()
	}
	
	if (typeof(response.data) == 'string') {
		try {
			JSON.parse(response.data)
		}catch(e) {
			return Promise.reject('服务器响应了无效的JSON数据')
		}
	}

	if (!response.config.custom.responseIntercept) {
		console.log('★★★ 跳过HTTP请求后拦截器 ★★★')
		return response.data
	}

	if (response && response.header && response.header.Date) {
		let respDateTime = dayjs(response.header.Date)
		console.log('★★★ HTTP请求响应时间 ★★★', respDateTime.format('YYYY-MM-DD HH:mm:ss'))
		store.commit('app/saveServerDatetime', respDateTime.format('YYYY-MM-DD HH:mm:ss'))

		let serverTimestamp = respDateTime.unix()
		let clientTimestamp = utils.timestamp()
		let sTimeStr = dayjs.unix(serverTimestamp).format('YYYY-MM-DD HH:mm:ss')
		let cTimeStr = dayjs.unix(clientTimestamp).format('YYYY-MM-DD HH:mm:ss')
		let time = (serverTimestamp - clientTimestamp)
		let absTime = Math.abs(time)

		if (time < 0) {
			console.log(
				`服务器时间：${sTimeStr} (${serverTimestamp})，客户端时间：${cTimeStr} (${clientTimestamp})，客户端时间比服务器快了：${absTime}秒`
				)
		} else if (time > 0) {
			console.log(
				`服务器时间：${sTimeStr} (${serverTimestamp})，客户端时间：${cTimeStr} (${clientTimestamp})，客户端时间比服务器慢了：${absTime}秒`
				)
		} else {
			console.log(
				`服务器时间：${sTimeStr} (${serverTimestamp})，客户端时间：${cTimeStr} (${clientTimestamp})，客户端时间和服务器时间一致`
				)
		}

		if (absTime > 120) {
			return Promise.reject('手机日期时间异常，请检查系统日期时间设置')
		}
	}

	if (response.statusCode != 200) {
		return Promise.reject(`网络请求失败（${response.statusCode}）`)
	}

	if (!response.data) {
		return Promise.reject('网络请求失败，服务器未返回响应数据')
	}

	if (parseInt(response.data.code) == 501 || parseInt(response.data.code) == 401) {
		store.commit('app/removeUserInfo')
		uni.showModal({
			content: '未登录或登录状态已失效，请重新登录',
			title: '系统提示',
			cancelText: '取消',
			confirmText: '登录',
			success(res) {
				if (res.confirm) {
					utils.openPage('/pkgLogin/pages/index/index')
				}
			}
		})
		return Promise.reject(`${response.data.message}`)
	} else if (response.data.code != undefined && (response.data.code != 200 || !response.data.success)) {
		if (response.data.code != undefined) {
			return Promise.reject(`${response.data.message}`)
		}
		return Promise.reject(`${response.data.message}（${response.statusCode}）`)
	} else if (response.data.errno != undefined && response.data.errno != 0) {
		return Promise.reject(`${response.data.errmsg}（${response.data.errno}）`)
	}

	return response.data
}, (response) => {
	console.log('★★★ HTTP请求响应失败 ★★★', response)

	if (typeof(response) == 'string') {
		return Promise.reject(response)
	}

	if (response && response.config && response.config.custom.showLoading) {
		uni.hideLoading()
	}

	if (response.errMsg) {
		let msg
		if (response.errMsg == 'request:fail ') {
			msg = '网络请求失败，请检查网络连接是否可用'
		} else if (response.errMsg == 'request:fail timeout') {
			msg = '网络请求失败，请求超时退出'
		} else if (typeof(response.errMsg) == 'string') {
			msg = response.errMsg
		} else {
			msg = JSON.stringify(response.errMsg)
		}
		return Promise.reject(msg)
	} else {
		return Promise.reject(response)
	}
})

initHttpConfig('luch-request.js')

export default http
